const path = require('path')
const fs = require('fs').promises
const mime = require('mime')
const {
    createReadStream
} = require('fs')
/**
 * 静态资源处理中间件
 */
module.exports = (publicPath) => {
    return async (ctx, next) => {

        let doFileHandle = async (absPath) => {

            try {
                let statObj = await fs.stat(absPath)
                if (statObj.isFile()) {
                    //如果是文件直接返回
                    //不给下载头
                    let type = mime.getType(absPath)
                    ctx.set('Content-Type', type + ';charset=utf-8')
                    ctx.body = createReadStream(absPath)
                } else {
                    let _absPath = path.join(absPath, 'index.html')
                    await doFileHandle(_absPath)
                }
            } catch (error) {
                //文件不存在
                await next()
            }
        }
        let absPath = path.join(publicPath, ctx.path)
        await doFileHandle(absPath)

    }
}